package com.jfinal.bbsapp.common.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jfinal.kit.StrKit;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;

public class CORSInterceptor implements Interceptor {
    @Override
    public void intercept(Invocation inv) { 	
    	 Controller controller = inv.getController();
         HttpServletRequest request = controller == null ? null : controller.getRequest();
         if (request == null) {
        	 inv.invoke();
			 return;
         }
   
         String origin = request.getHeader("origin");
         String corsHeaders = request.getHeader("access-control-request-headers");
         String corsMethod = request.getHeader("access-control-request-method");
   
         HttpServletResponse response = controller.getResponse();
         response.setHeader("Access-Control-Allow-Origin", StrKit.isBlank(origin) ? "*" : origin);
         response.setHeader("Access-Control-Allow-Credentials", "true");
         response.setHeader("Access-Control-Allow-Headers", StrKit.isBlank(corsHeaders) ? "*" : corsHeaders);
         response.setHeader("Access-Control-Allow-Methods", StrKit.isBlank(corsMethod) ? "*" : corsMethod);
         response.setHeader("Access-Control-Max-Age", "86400");
   
         if ("OPTIONS".equals(request.getMethod().toUpperCase())) {
           controller.renderJson("{}");
           return;
         }
   
         inv.invoke();
    }
}
